from sqlalchemy import func
import os
import base64
import json
import re
import requests
from flask import current_app

from app.core.extensions import db
from app.models.user import User, ShareRelation


def update_user_info(request_from):
    data = request_from.get_json()
    user_id = data.get('user_id')
    try:
        user = User.query.get(user_id)
        if not user:
            return {"code": 0, "msg": "用户不存在"}

        # 更新用户信息
        if 'nick_name' in data:
            user.nick_name = data['nick_name']
        if 'avatar_url' in data:
            user.avatar_url = data['avatar_url']
        if 'gender' in data:
            user.gender = data['gender']
        if 'country' in data:
            user.country = data['country']
        if 'province' in data:
            user.province = data['province']
        if 'city' in data:
            user.city = data['city']
        if 'mobile' in data:
            user.mobile = data['mobile']

        db.session.commit()

        return {
            "code": 1,
            "msg": "更新成功",
            "data": {
                "userInfo": user.to_dict()
            }
        }

    except Exception as e:
        return {"code": 0, "msg": f"服务器错误: {str(e)}"}


def get_usage_count(user_id):
    try:
        user = User.query.get(user_id)
        if not user:
            return {"code": 0, "msg": "用户不存在"}

        return {
            "code": 1,
            "msg": "获取成功",
            "data": {
                "usage_count": user.usage_count
            }
        }

    except Exception as e:
        return {"code": 0, "msg": f"服务器错误: {str(e)}"}


def get_user_profile(user_id):
    try:
        user = User.query.get(user_id)
        if not user:
            return {"code": 0, "msg": "用户不存在"}

        return {
            "code": 1,
            "msg": "获取成功",
            "data": {
                "userInfo": user.to_dict(),
                "is_dealer": False
            }
        }

    except Exception as e:
        return {"code": 0, "msg": f"服务器错误: {str(e)}"}


def get_user_top():
    try:
        # 第一步：统计 sharer_id 出现次数（就是邀请人数）
        sharer_counts = (
            db.session.query(
                ShareRelation.sharer_id,
                func.count(ShareRelation.invitee_id).label('invite_count')
            )
            .group_by(ShareRelation.sharer_id)
            .order_by(func.count(ShareRelation.invitee_id).desc())
            .limit(10)
            .all()
        )

        if not sharer_counts:
            return {
                "code": 1,
                "msg": "暂无数据",
                "data": {
                    "list": []
                }
            }

        # 第二步：提取出 sharer_id 列表
        sharer_ids = [item.sharer_id for item in sharer_counts]

        # 第三步：根据 sharer_id 查询用户信息
        users = User.query.filter(User.user_id.in_(sharer_ids)).all()
        user_dict = {user.user_id: user for user in users}  # 方便通过 id 找用户信息

        # 第四步：组装返回数据
        result = []
        for idx, item in enumerate(sharer_counts, start=1):
            user = user_dict.get(item.sharer_id)
            if user:
                result.append({
                    "rank": idx,  # 排名
                    "id": user.user_id,
                    "nickname": user.nick_name if hasattr(user, 'nick_name') else '',
                    "avatar_url": user.avatar_url if hasattr(user, 'avatar_url') else '',
                    "amount": item.invite_count  # 邀请人数
                })

        return {
            "code": 1,
            "msg": "获取成功",
            "data": {
                "list": result
            }
        }

    except Exception as e:
        print(e)
        return {
            "code": 0,
            "msg": "服务器异常",
            "data": {}
        }


def validate_user(user_id):
    if not user_id or not str(user_id).strip():
        return None, "用户ID不能为空"

    try:
        user = User.query.get(user_id)
        if not user:
            return None, "用户不存在"
        if user.usage_count < 1:  # 修复逻辑
            return None, "剩余使用次数不足"
        return user, None
    except Exception as e:
        current_app.logger.error(f"验证用户失败: {str(e)}")
        return None, "用户验证失败"
